package com.ddc.study.feature.main.project;

import com.ddc.study.R;
import com.ddc.study.entity.Tree;
import com.ddc.study.net.NetworkUtil;
import com.ddc.study.net.response.BaseResponse;

import java.util.List;

import androidx.annotation.NonNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created on 2018/5/22.
 *
 * @author lshun
 * @version 1.0
 */
class ProjectPresenter extends ProjectContract.IPresenter {
    @Override
    void loadProjectTree() {
        NetworkUtil.getProjectTree().enqueue(new Callback<BaseResponse<List<Tree>>>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<List<Tree>>> call,
                                   @NonNull Response<BaseResponse<List<Tree>>> response) {
                if (!isViewAttached()) return;
                if (!response.isSuccessful()) {
                    getView().loadProjectTreeFailed("请求失败(" + response.code() + ")");
                    return;
                }
                BaseResponse<List<Tree>> body = response.body();
                if (body == null) {
                    getView().loadProjectTreeFailed(getView().getStringValue(R.string.response_empty_body));
                } else if (!body.isSuccess()) {
                    getView().loadProjectTreeFailed(body.getErrorMsg());
                } else {
                    getView().loadProjectTreeSuccess(body.getData());
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<List<Tree>>> call,
                                  @NonNull Throwable t) {
                if (isViewAttached()) getView().loadProjectTreeFailed(t.getMessage());
            }
        });
    }
}
